package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 * @Name LoginCheckInterceptor
 * @Author stella
 * @Date 2023-03-01 4:03 PM
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1-获取session中的员工信息
        HttpSession session = request.getSession();
        Employee employee = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        // 2-判断是否登陆
        if (employee == null) {
            // 为空，返还结果error
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            // 把结果转换成json，使用阿里json
            String json = JSON.toJSONString(resultInfo);
            // 通过reponse响应
            response.setContentType("application/json;charset=utf-8"); // 告诉前端MIME类型和字符集编码
            response.getWriter().write(json);
            //return false 拦截
            return false;
        }
        // 3-登陆成功 放行
        EmployeeHolder.set(employee);//储存到当前线程

        return true;
    }

    //响应之前，删除线程内的员工对象
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
